#!/bin/bash
# shellcheck disable=SC2034

PRODUCT=$(cat /sys/class/dmi/id/product_name)
VENDOR=$(cat /sys/class/dmi/id/sys_vendor)

if [ -x "$(command -v sk-unlock-pacman)" ]; then
    sk-unlock-pacman
fi

PYTHON_SITE_PACKAGES_PATH=$(python3 -c "import site; print(site.getsitepackages()[0])")
HHD_PATH="${PYTHON_SITE_PACKAGES_PATH}/hhd"
HHD_ORANGE_INIT_PATH="${HHD_PATH}/device/orange_pi/__init__.py"
HHD_OUTPUTS_PATH="${HHD_PATH}/plugins/outputs.py"
echo "HHD_PATH: $HHD_PATH"

# 重试函数
function retry() {
    local max_attempts=5
    local attempt=1
    local wait_time=2

    while [ $attempt -le $max_attempts ]; do
        echo "Attempt $attempt of $max_attempts..."
        if "$@"; then
            return 0
        fi
        attempt=$((attempt + 1))
        if [ $attempt -le $max_attempts ]; then
            echo "Waiting $wait_time seconds before retrying..."
            sleep $wait_time
            wait_time=$((wait_time * 2)) # 指数退避
        fi
    done
    return 1
}

function restart_hhd_gamer() {
    status=$(systemctl is-enabled hhd@gamer 2>/dev/null)
    if [[ "$status" == "enabled" ]]; then
        echo "Restart hhd@gamer"
        systemctl restart hhd@gamer
    fi
}

# Try patches in order until one succeeds
# Usage: try_patches_in_order <target_dir> <patch_urls_array_name>
# Returns: 0 if any patch succeeded, 1 if all failed
function try_patches_in_order() {
    local target_dir="$1"
    local -n patch_urls_ref="$2"

    # Create backup directory
    local backup_dir="/tmp/hhd_patch_backup_$$"
    if ! mkdir -p "$backup_dir"; then
        echo "Failed to create backup directory"
        return 1
    fi

    # Backup entire target directory
    if ! cp -a "$target_dir" "$backup_dir/"; then
        echo "Failed to create backup"
        rm -rf "$backup_dir"
        return 1
    fi

    local patch_applied=false
    local target_dir_name
    target_dir_name=$(basename "$target_dir")

    # Try patches in order
    for patch_url in "${patch_urls_ref[@]}"; do
        local patch_name
        patch_name=$(basename "$patch_url")
        echo "Trying patch: $patch_name"

        # Try to download and apply patch
        if retry curl -sSL "$patch_url" | patch -d "$target_dir" -p1 --batch --forward --no-backup-if-mismatch; then
            echo "Patch $patch_name applied successfully"
            patch_applied=true
            break
        else
            echo "Patch $patch_name failed, restoring backup..."
            # Restore backup
            if ! rm -rf "$target_dir" || ! cp -a "$backup_dir/$target_dir_name" "$target_dir"; then
                echo "Critical error: Failed to restore backup"
                rm -rf "$backup_dir"
                return 1
            fi
        fi
    done

    # Clean up backup directory
    rm -rf "$backup_dir"

    if [[ "$patch_applied" == true ]]; then
        return 0
    else
        echo "All patches failed"
        return 1
    fi
}

function apply_hhd_patch_win5() {
    local path_base_url="https://gitee.com/honjow/sk-chos-scripts/raw/master/patchs"
    
    local path_win5_g1=(
        "${path_base_url}/hhd-win5.patch"
        )
    local path_win5_g2=(
        # "${path_base_url}/hhd-win5-02.patch"
        "${path_base_url}/hhd-win5-02-rev.patch"
        )
    local path_win5_g3=(
        "${path_base_url}/hhd-win5-03.patch"
        )
    local path_win5_g4=(
        "${path_base_url}/hhd-win5-04.patch"
        )
    if [[ "$PRODUCT" == "G1618-05" || "$PRODUCT" == "G1617-01" ]]; then
        try_patches_in_order "$HHD_PATH" path_win5_g1
        try_patches_in_order "$HHD_PATH" path_win5_g2
        try_patches_in_order "$HHD_PATH" path_win5_g3
        try_patches_in_order "$HHD_PATH" path_win5_g4
    fi
}

echo "start to modify hhd@gamer"
# sudo sed -i 's/grab=True/grab=False/g' /usr/lib/python3.13/site-packages/hhd/device/gpd/win/base.py

# grep "grab=False" /usr/lib/python3.13/site-packages/hhd/device/gpd/win/base.py

patch_applied=false

apply_hhd_patch_win5 && patch_applied=true

if [[ "$patch_applied" == true ]]; then
    echo "Some hhd patches applied successfully"
    restart_hhd_gamer
else
    echo "No hhd patches were applied"
    exit 1
fi